let readBtn = document.getElementById('read');
let sessionStoreList = document.getElementById('sessionStoreList');
let writeBtn = document.getElementById('write');
let writeArea = document.getElementById('writeArea');
let locateAddress = document.getElementById('locateAddress');
let needWriteItems = {}
writeArea.style.display = 'none'


let executeCode = function () {
  let sessionStoreItem = {}
  for (let prop in sessionStorage) {
    if (typeof sessionStorage[prop] !== 'function' && prop !== 'length') {
      sessionStoreItem[prop] = sessionStorage[prop]
    }
  }
  return sessionStoreItem
}



readBtn.onclick = function () {


  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      func: executeCode
    })
      .then(([sessionStoreItem]) => {
        let divFrag = document.createDocumentFragment()
        needWriteItems = sessionStoreItem?.result || {};
        for (let prop in needWriteItems) {
          divFrag.appendChild(createSessionItemLi(prop, needWriteItems[prop]))
        }
        sessionStoreList.innerHTML = ""
        sessionStoreList.appendChild(divFrag)
        writeArea.style.display = 'block'
      });
  })
}

function createSessionItemLi(prop, val) {
  let li = document.createElement('li')
  let input = document.createElement('input')
  input.setAttribute('type', 'text')
  input.setAttribute('value', val)
  li.appendChild(document.createTextNode(prop + ':'))
  li.appendChild(input)
  return li
}

writeBtn.onclick = function () {
  let locateVal = locateAddress.value
  chrome.tabs.query({})
  .then((tabs)=>{
    if (!locateVal) {
      tabs.forEach(tab=>writeSessionStore(tab))
      alert('SessionStorage应该成功写入到所有tabs了，确认下，保险点！')
      return false;
    }
    let needWriteTab;
    for (let tab of tabs) {
      if (tab && tab.url && tab.url.includes(locateVal)) {
        needWriteTab = tab
        break
      }
    }
    if (!needWriteTab) return false
    writeSessionStore(needWriteTab)
    alert('SessionStorage应该成功写入到' + locateVal + '了，确认下，保险点！')
  })
}

function writeSessionStore(needWriteTab) {
  for (let prop in needWriteItems) {
    chrome.scripting.executeScript({
      target: { tabId: needWriteTab.id },
      args:[prop,needWriteItems[prop]],
      func: (prop,value)=>{
        sessionStorage.setItem(prop, value);
        return prop;
      },
    })
      .then((result) => {
        console.log(prop + '写入成功！', result)
      });
  }
}

